const mongoose = require('mongoose');

const videoReviewSchema = new mongoose.Schema(
  {
    review: {
      type: String,
      required: [true, 'VideoReview cannot be empty'],
      trim: true,
    },
    rating: {
      type: Number,
      min: 1,
      max: 5,
    },
    createAt: {
      type: Date,
      default: Date.now(),
    },
    video: {
      type: mongoose.Schema.ObjectId,
      ref: 'Video',
      required: [true, 'Review must belong to a Video'],
    },
    user: {
      type: mongoose.Schema.ObjectId,
      ref: 'User',
      required: [true, 'Review must belong to a user'],
    },
  },
  {
    toJSON: { virtuals: true },
    toObject: { virtuals: true },
  }
);
videoReviewSchema.index({ createAt: 1, user: 1 }, { unique: true });

videoReviewSchema.pre(/^find/, function (next) {
  this.populate({
    path: 'user',
    select: 'name photo',
  });
  next();
});

// videoReviewSchema.statics.calcAverageRatings = async function (videoId) {
//   const stats = await this.aggregate(
//     {
//       $match: { video: videoId },
//     },
//     {
//       $group: {
//         _id: '$video',
//         nRating: { $sum: 1 },
//         avgRating: { $avg: '$rating' },
//       },
//     }
//   );
//   if (stats.length > 0) {
//     await Video.findByIdAndUpdate(videoId, {
//       ratingsAverage: stats[0].nRating,
//       ratingsQuantity: stats[0].avgRating,
//     });
//   } else {
//     await Video.findByIdAndUpdate(videoId, {
//       ratingsQuantity: 0,
//       ratingsAverage: 4.5,
//     });
//   }
// };
// videoReviewSchema.post('save', function () {
//   this.constructor.calcAverageRatings(this.video);
// });
videoReviewSchema.pre(/^findOneAnd/, async function (next) {});

const VideoReview = mongoose.model('VideoReview', videoReviewSchema);

module.exports = VideoReview;
